<template>
  <div class="video-live">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel" :class="{ 'ptz-hidden': !showPTZControl }">
        <!-- 摄像头目录树 -->
        <div class="tree-section">
          <CameraTreeView
            :data="treeData"
            :default-expand-all="true"
            :show-header="true"
            :show-checkboxes="false"
            @control-ptz="handleControlPTZ"
            @node-click="handleNodeClick"
            @refresh="handleRefreshTree"
          />
        </div>
        
        <!-- 云台控制 -->
        <div 
          class="ptz-section" 
          v-if="showPTZControl && selectedCamera?.ptzEnable"
          :class="{ 'ptz-animate-in': showPTZControl }"
        >
          <PTZControl
            :camera="selectedCamera"
            @ptz-command="handlePTZCommand"
            @preset-change="handlePresetChange"
          />
        </div>
      </div>

      <!-- 中间内容区域 -->
      <div class="center-panel">
        <!-- 实时视频流 -->
        <LiveStreamViewer
          ref="liveStreamRef"
          :default-layout="4"
          :cameras="availableCameras"
          @camera-added="handleCameraAdded"
          @camera-removed="handleCameraRemoved"
          @control-ptz="handleControlPTZ"
          @start-record="handleStartRecord"
          @stop-record="handleStopRecord"
          @drop="handleDrop"
        />
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { success, info } from '@/utils/toast'
import CameraTreeView from '@/components/CameraTreeView.vue'
import PTZControl from '@/components/PTZControl.vue'
import LiveStreamViewer from '@/components/LiveStreamViewer.vue'
import { useCameraStore } from '@/stores/camera'
import { $ptzControl } from '@/api/nvr'
import type { PtzControl } from '@/types'
// 接口定义
interface Camera {
  id: string
  name: string
  ip: string
  status: 'online' | 'offline'
  url?: string
  type?: 'camera'
  nvrId?: number
  subEquId?: number
  ptzEnable?: boolean  // 是否支持云台控制
}

interface CameraTreeNode {
  id: string
  name: string
  type: 'folder' | 'camera'
  status?: 'online' | 'offline'
  ip?: string
  url?: string
  children?: CameraTreeNode[]
  parentId?: string | number
  hasMapMarker?: boolean
  nvrId?: number
  subEquId?: number
  ptzEnable?: boolean  // 是否支持云台控制
}

// Store
const cameraStore = useCameraStore()

// 响应式数据
const liveStreamRef = ref()
const selectedCamera = ref<Camera | null>(null)
const showPTZControl = ref(false) // 控制云台组件的显示状态

// 模拟摄像头数据
const availableCameras = ref<Camera[]>([])

// 目录树数据
const treeData = ref<CameraTreeNode[]>([])


// 方法

const handleControlPTZ = (camera: Camera | CameraTreeNode) => {
  if ('type' in camera && camera.type === 'camera') {
    selectedCamera.value = {
      id: camera.id,
      name: camera.name,
      ip: camera.ip || '',
      status: camera.status || 'offline',
      url: camera.url,
      type: 'camera',
      nvrId: camera.nvrId,
      subEquId: camera.subEquId,
      ptzEnable: camera.ptzEnable
    }
  } else {
    selectedCamera.value = camera as Camera
  }
  
  // 显示云台控制组件
  showPTZControl.value = true
  success(`已选择摄像头进行云台控制：${selectedCamera.value.name}`)
}

const handleNodeClick = (node: CameraTreeNode) => {
  console.log('Node clicked:', node)
}

const handleRefreshTree = () => {
  success('目录树已刷新')
}

const handleCameraAdded = (camera: Camera, slotIndex: number) => {
  console.log(`主页面接收到摄像头添加事件: ${camera.name} 在槽位 ${slotIndex}`)
  // 不自动显示云台控制组件，等待用户点击箭头按钮
  showPTZControl.value = false
}

const handleCameraRemoved = (camera: Camera, slotIndex: number) => {
  console.log(`摄像头 ${camera.name} 已从槽位 ${slotIndex} 移除`)
  // 如果移除的是当前选中的摄像头，清空云台控制
  if (selectedCamera.value?.id === camera.id) {
    selectedCamera.value = null
    showPTZControl.value = false // 隐藏云台控制组件
    info(`摄像头 ${camera.name} 已移除，云台控制已清空`)
  }
}



const handleStartRecord = (cameras: Camera[]) => {
  console.log('开始录制摄像头:', cameras.map(c => c.name))
  success(`开始录制 ${cameras.length} 个摄像头`)
}

const handleStopRecord = (cameras: Camera[]) => {
  console.log('停止录制摄像头:', cameras.map(c => c.name))
  info('已停止录制')
}

const handlePTZCommand = async (command: number, params?: any) => {
  console.log('PTZ命令:', command, params)
  try {
    // 构建云台控制参数
    const ptzControlData: PtzControl = {
      nvrId: params?.nvrId || 0,
      subEquId: params?.subEquId,
      command: command,
      speed: params?.speed || 50 // 默认速度
    }
    console.log('发送云台控制命令:', ptzControlData)
    // 调用云台控制API
    await $ptzControl(ptzControlData)
    
  } catch (error) {
    console.error('云台控制命令执行失败:', error)
  }
}

const handlePresetChange = (preset: any) => {
  console.log('预置位变化:', preset)
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  const cameraData = event.dataTransfer?.getData('text/plain')
  if (cameraData) {
    try {
      const camera = JSON.parse(cameraData)
      if (liveStreamRef.value) {
        liveStreamRef.value.addCamera(camera)
      }
    } catch (error) {
      console.error('拖拽数据解析失败:', error)
    }
  }
}

// 生命周期
onMounted(() => {
  console.log('视频监控页面已加载')
  cameraStore.fetchCameraList()
})

onUnmounted(() => {
  console.log('视频监控页面已卸载')
})
</script>

<style scoped>
.video-live {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.page-header {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 12px;
  padding: 12px;
  min-height: 0;
}

.left-panel {
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

/* 当云台控制隐藏时，目录树区域占满整个左侧面板 */
.left-panel.ptz-hidden .tree-section {
  flex: 1;
  min-height: 0;
}

.center-panel {
  flex: 1;
  min-width: 0;
}

.tree-section {
  flex: 1;
  min-height: 0;
}

.ptz-section {
  height: 380px;
  flex-shrink: 0;
}


/* 响应式设计 */
@media (max-width: 1400px) {
  .left-panel {
    width: 300px;
  }
}

@media (max-width: 1200px) {
  .left-panel {
    width: 280px;
  }
}

@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-panel {
    width: 100%;
    flex-direction: row;
    height: 400px;
  }
  
  .tree-section {
    flex: 1;
    height: 100%;
  }
  
  .ptz-section {
    width: 320px;
    height: 380px;
    flex-shrink: 0;
  }
  
  .center-panel {
    height: 60vh;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 16px;
  }
  
  .main-content {
    padding: 8px;
    gap: 8px;
  }
  
  .left-panel {
    flex-direction: column;
    height: 500px;
  }
  
  .tree-section {
    flex: 1;
  }
  
  .ptz-section {
    height: 300px;
    width: 100%;
  }
  
  .center-panel {
    height: 50vh;
  }
}

/* 云台控制组件动画 */
.ptz-section {
  transition: all 0.3s ease-in-out;
  transform: translateY(0);
  opacity: 1;
}

.ptz-animate-in {
  animation: slideInFromBottom 0.4s ease-out;
}

@keyframes slideInFromBottom {
  0% {
    transform: translateY(100%);
    opacity: 0;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 左侧面板隐藏云台控制时的样式 */
.left-panel.ptz-hidden .ptz-section {
  display: none;
}

.left-panel:not(.ptz-hidden) .tree-section {
  flex: 1;
  min-height: 0;
}
</style>